<template>
  <div class="main" style="height: 100%">
    <div>
      <div class="topSearch">
        <span>
          店铺名称:
          <el-input
            size="small"
            prefix-icon="el-icon-search"
            style="width: 300px; margin-right: 10px"
            v-model="params.storeName"
            clearable
            placeholder="请输入店铺名称"
          ></el-input>
        </span>

        <span>
          仓库:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder="请选择仓库名称"
            v-model="params.areaId"
          >
            <el-option
              v-for="(e, i) in areaData"
              :label="e.areaName"
              :key="i"
              :value="e.area"
            ></el-option>
          </el-select>
        </span>
        <span>
          品牌:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder="请选择品牌"
            v-model="params.systemType"
          >
            <el-option
              :value="item.id"
              :label="item.systemName"
              :key="item.id"
              v-for="item in systemList"
            ></el-option>
          </el-select>
        </span>
        <!-- <span>
          材料付款时间:
          <el-date-picker
            style="width: 230px"
            clearable
            size="small"
            value-format="yyyy-MM-dd"
            placeholder="请选择材料付款时间"
            v-model="data.materialPayTime"
          ></el-date-picker>
        </span> -->
        <span>
          货架去货日期:
          <el-date-picker
            v-model="sateValue"
            type="daterange"
            range-separator="至"
            clearable
            size="small"
            @change="selectTime"
            style="width: 200px"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          >
          </el-date-picker>
        </span>
        <!-- <span>
          接收回款方式:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder="接收回款方式"
            v-model="params.areaId"
          >
            <el-option
              v-for="(e, i) in areaData"
              :label="e.areaName"
              :key="i"
              :value="e.area"
            ></el-option>
          </el-select>
        </span>
        <span>
          报销状态:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder=" 报销状态"
            v-model="params.status"
          >
            <el-option
              v-for="(e, i) in baoXiaoStatus"
              :label="e.name"
              :key="i"
              :value="e.value"
            ></el-option>
          </el-select>
        </span>
        <span>
          责任主体:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder=" 责任主体"
            v-model="params.operator"
          >
            <el-option
              v-for="(e, i) in responsibility"
              :label="e.optione"
              :key="i"
              :value="e.id"
            ></el-option>
          </el-select>
        </span>
        <span>
          报销接收人:
          <el-select
            clearable
            size="small"
            style="width: 200px"
            placeholder=" 报销接收人"
            v-model="params.areaId"
          >
            <el-option
              v-for="(e, i) in areaData"
              :label="e.areaName"
              :key="i"
              :value="e.area"
            ></el-option>
          </el-select>
        </span> -->
        <span>
          <el-button size="mini" type="primary" @click="searchList"
            >查询</el-button
          >
          <el-button
            size="small"
            style="width: 80px; margin-left: 20px"
            @click="reset"
            >重置
          </el-button>
          <!-- <el-button size="mini" type="primary" @click="addReimburse">
            新增报销
          </el-button> -->
        </span>

        <!-- <el-input
          size="small"
          prefix-icon="el-icon-search"
          style="width: 300px; margin-right: 10px"
          v-model="params.storeName"
          clearable
          placeholder="请输入店铺名称"
        ></el-input>
        <el-select
          filterable
          remote
          :remote-method="remoteMethod"
          value-key="creator"
          clearable
          v-model="params.creator"
          size="small"
          style="width: 300px; margin-right: 10px"
          placeholder="请输入创建人"
        >
          <el-option
            v-for="(item, i) in creatorList"
            :key="i"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
        <el-select
          size="small"
          style="width: 200px; margin-right: 10px"
          clearable
          v-model="params.area"
          filterable
          placeholder="请选择省份"
        >
          <el-option
            v-for="item in provinceOptions"
            :key="item.area"
            :label="item.areaName"
            :value="item.area"
          >
          </el-option>
        </el-select>
        <el-select
          v-model="params.systemType"
          placeholder="请按品牌方搜索"
          size="small"
          style="width: 200px"
        >
          <el-option
            :value="item.id"
            :label="item.systemName"
            :key="item.id"
            v-for="item in systemList"
          ></el-option>
        </el-select>
        <el-select
          size="small"
          style="width: 200px; margin-right: 10px"
          clearable
          v-model="params.status"
          filterable
          placeholder="请选择审核状态"
        >
          <el-option label="未完结" value="0"> </el-option>
          <el-option label="主管已审核" value="1"> </el-option>
          <el-option label="财务已审核" value="2"> </el-option>
        </el-select> -->
        <!--        <el-select size="small" style="width: 200px;margin-right: 10px;" clearable v-model="params.storeType" filterable-->
        <!--                   placeholder="请选择店铺类型">-->
        <!--          <el-option label="新增店铺"-->
        <!--                     value="1">-->
        <!--          </el-option>-->
        <!--          <el-option label="老店翻新"-->
        <!--                     value="2">-->
        <!--          </el-option>-->
        <!--        </el-select>-->
      </div>
      <div v-if="false">
        <el-button
          style="
            position: absolute;
            top: 10px;
            right: 140px;
            background-color: #f56c6c;
            color: #ffffff;
          "
          v-if="userName == '曹紫芳' || userName == '赵伟清'"
          @click="closeReimburse"
        >
          关闭报销
        </el-button>
        <!-- <el-button
          style="
            position: absolute;
            top: 10px;
            right: 20px;
            background-color: #66b1ff;
            color: #ffffff;
          "
          @click="addReimburse"
        >
          新增报销
        </el-button> -->
      </div>
      <div></div>
    </div>
    <div style="margin-top: 20px">
      <el-table
        :data="dataList"
        :height="maxHeight"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-spinner="el-icon-loading"
        tripe
        border
        tooltip-effect="dark"
        :headerCellStyle="{
          textAlign: 'center',
          fontWeight: 400,
          background: '#66b1ff',
          color: 'white',
        }"
        :cellStyle="{
          textAlign: 'center',
          fontSize: '12px',
        }"
      >
        <!-- v-if="item.key !== 'storeName' && item.key !== 'systemName'" -->
        <el-table-column
          type="index"
          label="序号"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="storeName"
          label="店铺名称"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="systemName"
          label="品牌"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="areaName"
          label="仓库"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="materialTotal"
          label="材料汇总"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="shelfTotal"
          label="货架汇总"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="materialsLalamoveFee"
          label="材料货拉拉费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="materialsDeliveryFee"
          label="材料快递费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="materialsForkliftFee"
          label="材料叉车费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="materialsOther"
          label="材料其他"
          width="100px"
        ></el-table-column>
        <!-- <el-table-column
          prop="materialsOther"
          label="材料付款时间 没有"
          width="100px"
        ></el-table-column> -->
        <el-table-column
          prop="shelfLalamoveFee"
          label="货架货拉拉费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="shelfDeliveryFee"
          label="货架快递费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="shelfForkliftFee"
          label="货架叉车费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="tempFee"
          label="零时工费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="outInstallationFee"
          label="外请安装费"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="inInstallationFee"
          label="内安装费"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="doorFee"
          label="上门费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="afterFee"
          label="售后费用"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="shelfOtherFee"
          label="货架其他"
          width="100px"
        ></el-table-column>
        <el-table-column
          prop="deliveryDate"
          label="货架去货日期"
          width="100px"
        ></el-table-column>

        <!-- <el-table-column
          v-for="(level, colIndex) in dynamicHeaders"
          :key="colIndex"
          :label="level"
          align="center"
          min-width="120px"
        >
          <template #default="scope">
            {{ scope.row.listMap[level] || 0 }}
          </template>
        </el-table-column> -->

        <!-- <el-table-column prop="financeName" label="品牌"> </el-table-column> -->
        <!-- <el-table-column prop="levelName" label="仓库"> </el-table-column>
        <el-table-column prop="systemName" label="材料汇总"> </el-table-column>
        <el-table-column prop="optionerName" label="货架汇总">
        </el-table-column>
        <el-table-column prop="optionerName" label="材料货拉拉费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="材料快递费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="材料叉车费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="材料其他">
        </el-table-column>
        <el-table-column prop="optionerName" label="材料付款时间">
        </el-table-column>
        <el-table-column prop="optionerName" label="货架货拉拉费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="货架快递费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="货架叉车费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="零时工费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="外请安装费">
        </el-table-column>
        <el-table-column prop="optionerName" label="内安装费">
        </el-table-column>
        <el-table-column prop="optionerName" label="上门费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="售后费用">
        </el-table-column>
        <el-table-column prop="optionerName" label="货架其他">
        </el-table-column>
        <el-table-column prop="optionerName" label="货架去货日期">
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column
          prop="systemName"
          label="店铺统计时间 没有"
        ></el-table-column> -->

        <!-- <el-table-column label="明细操作" width="180px" fixed="right">
          <template slot-scope="scope">
            <el-link
              type="primary"
              @click="review(scope.row)"
              v-prevent-re-click
              style="margin-right: 10px"
              >审核
            </el-link>
            <el-link
              type="warning"
              @click="transferFunds(scope.row)"
              v-prevent-re-click
              style="margin-right: 10px"
              >打款
            </el-link>
            <el-link
              type="info"
              @click="checkDetail(scope.row)"
              v-prevent-re-click
              style="margin-right: 10px"
              >取消
            </el-link>
            <el-link type="danger" @click="deteItme" v-prevent-re-click
              >删除</el-link
            >
          </template>
        </el-table-column> -->
        <!--        <el-table-column label="操作" fixed="right" min-width="100px">-->
        <!--          <template slot-scope="scope">-->
        <!--            <el-link style='font-size:12px' type="success" @click="confirmOrder(scope.row.id)"-->
        <!--                     v-if='scope.row.status !== 1'>确认完成-->
        <!--            </el-link>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
      </el-table>
    </div>
    <div style="padding-top: 20px">
      <el-pagination
        style="border-top: 1px solid #eee; padding-top: 20px"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="params.pageNumber"
        :page-sizes="[20, 30, 50]"
        :page-size="20"
        layout="total, sizes, prev, pager, next, jumper"
        align="right"
        :total="params.totalCount"
      >
      </el-pagination>
    </div>
    <el-dialog
      :close-on-click-modal="false"
      :title="dialogTitle"
      :visible.sync="ledgerStatus"
      width="90%"
      center
      :show-close="false"
      top="10px"
      :before-close="handleClose"
    >
      <div class="feeType">
        <div class="typeList" v-if="resFee && authority.includes(998)">
          <span>公里数</span><span>{{ decimalCount }}</span>
        </div>
        <div class="typeList" v-if="authority.includes(998)">
          <span>报价单运费</span><span>{{ resFee }}</span>
        </div>
        <div
          :class="chooseDateIndex == item.financeId ? 'active' : ''"
          class="typeList"
          :style="{ color: item.financeTypeStatus === 0 ? 'black' : 'red' }"
          @click="chooseType(item.financeId)"
          v-for="item in typeList"
        >
          <span>{{ item.financeName }}</span
          ><span>{{ item.financeTotal }}</span>
        </div>
      </div>
      <div class="feeTable">
        <el-table
          :data="feeData"
          @selection-change="handleSelectionChange"
          style="margin-top: 10px; height: 600px; overflow: scroll"
          :headerCellStyle="{
            textAlign: 'center',
            fontWeight: 400,
            background: '#66b1ff',
            color: 'white',
          }"
          :cellStyle="{
            textAlign: 'center',
            fontSize: '12px',
          }"
        >
          <el-table-column
            prop="id"
            label="单号"
            width="70px"
          ></el-table-column>
          <el-table-column prop="userName" label="申请人"></el-table-column>
          <el-table-column
            prop="createTime"
            label="申请日期"
            width="95px"
          ></el-table-column>
          <el-table-column
            prop="financeLevelTypeName"
            label="费用类型"
          ></el-table-column>
          <el-table-column
            prop="optionerName"
            label="承担主体"
          ></el-table-column>
          <el-table-column
            prop="matter"
            label="费用说明"
            width="230px"
          ></el-table-column>
          <el-table-column prop="money" label="花费"></el-table-column>
          <el-table-column prop="remark" label="备注"></el-table-column>
          <el-table-column
            prop="rejectReason"
            label="驳回原因"
          ></el-table-column>
          <el-table-column label="凭证" width="200px">
            <template slot-scope="scope">
              <el-image
                v-for="i in scope.row.proof"
                :key="i"
                style="width: 50px; height: 50px"
                :src="host + i"
                :preview-src-list="scope.row.proof.map((img) => host + img)"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="付款方式" width="210px">
            <template slot-scope="scope">
              <div
                v-if="!scope.row.payUrl"
                style="
                  display: flex;
                  flex-direction: column;
                  justify-content: space-around;
                  height: 100px;
                  width: 210px;
                "
              >
                <span>卡号：{{ scope.row.cardNo }}</span>
                <span>开户行：{{ scope.row.bankName }}</span>
                <span>持卡人：{{ scope.row.cardName }}</span>
              </div>
              <div v-if="scope.row.payUrl">
                <el-image
                  style="width: 50px; height: 50px"
                  :src="host + scope.row.payUrl"
                  :preview-src-list="Array(host + scope.row.payUrl)"
                >
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="财务付款凭证">
            <template slot-scope="scope" v-if="scope.row.paidUrl">
              <el-image
                style="width: 50px; height: 50px"
                v-for="(item, index) in scope.row.paidUrl.split(',')"
                :src="host + item"
                :key="index"
                :preview-src-list="[host + item]"
              >
              </el-image>
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="审核人"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <div v-if="scope.row.status == 3" style="color: seagreen">
                已付款
              </div>
              <div v-if="scope.row.status == 2" style="color: #f5b330">
                待付款
              </div>
              <div v-if="scope.row.status == 0" style="color: #f5b330">
                待主管审核
              </div>
              <div v-if="scope.row.status == 1" style="color: orangered">
                已驳回
              </div>
              <div v-if="scope.row.status == 4" style="color: #66b1ff">
                待财务审核
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150px">
            <template slot-scope="scope">
              <div v-if="scope.row.status == 0 || scope.row.status == 4">
                <el-button
                  type="danger"
                  slot="reference"
                  size="small"
                  @click="reject(scope.row)"
                  v-if="
                    [996].some((value) => authority.includes(value)) &&
                    ![4].includes(scope.row.status)
                  "
                  >驳回
                </el-button>
                <el-button
                  type="danger"
                  slot="reference"
                  size="small"
                  @click="reject(scope.row)"
                  v-if="
                    [999].some((value) => authority.includes(value)) &&
                    scope.row.status == 4
                  "
                  >驳回
                </el-button>
                <el-button
                  type="primary"
                  size="small"
                  @click="directorAudit(scope.row, 4)"
                  style="margin-left: 10px"
                  v-if="
                    authority.includes(996) && ![4].includes(scope.row.status)
                  "
                  >通过
                </el-button>
              </div>
              <el-link
                v-if="scope.row.status == '1' && authority.includes(999)"
                style="color: red; margin-left: 15px"
                @click="deleteAudit(scope.row)"
                >删除
              </el-link>
              <el-link
                v-if="scope.row.status == '1'"
                style="color: orange; margin-left: 15px"
                @click="editAudit(scope.row)"
                >编辑
              </el-link>
              <el-link
                v-if="
                  [2, 3].includes(scope.row.status) && authority.includes(999)
                "
                style="text-decoration: none; font-size: 13px"
                type="primary"
                @click="comfirmAudit(scope.row, 3)"
                ><i class="el-icon-refresh-left"></i>撤回
              </el-link>
            </template>
          </el-table-column>
          <el-table-column
            type="selection"
            v-if="authority.includes(999)"
            :selectable="isRowSelectable"
            width="55"
          >
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ledgerStatus = false">返 回</el-button>
        <el-button
          style="position: absolute; right: 20px"
          type="primary"
          @click="checkPayType"
          v-if=" buttonShow"
          >财务上传打款凭证</el-button
        >
      </span>

      <el-dialog
        :close-on-click-modal="false"
        width="30%"
        title="财务付款凭证"
        :visible.sync="innerVisible"
        append-to-body
      >
        <div style="display: flex">
          <span style="margin-right: 30px">财务付款凭证:</span>
          <span style="color: gray; font-size: 12px"
            >(粘贴复制即可上传图片)</span
          >
        </div>
        <div class="div" style="display: flex; align-items: center">
          <div
            v-for="(v, i) in paidUrl"
            style="display: flex; align-items: center; margin-right: 10px"
          >
            <el-image
              :key="i"
              style="width: 50px; height: 50px"
              ref="preview"
              :src="host + v"
              :preview-src-list="[host + v]"
            >
            </el-image>
            <div @click="deletePaiedUrl(i)">
              <el-icon name="delete"></el-icon>
            </div>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="comfirmPay">已付款</el-button>
        </span>
      </el-dialog>
    </el-dialog>
    <add-reimburse ref="addDialog" @addStatus="receiveMessage"></add-reimburse>
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="closeDialog"
      center
      title="选择日期"
      width="30%"
    >
      日期：
      <el-date-picker
        v-model="time"
        type="date"
        size="small"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        style="width: 80%"
        placeholder="选择日期"
      >
      </el-date-picker>
      <span slot="footer">
        <el-button @click="closeDialog = false">取 消</el-button>
        <el-button type="primary" @click="comfirmClose">确定</el-button>
      </span>
      <span slot="footer" class="dialog-footer">
        <span style="display: block; color: red"
          >*确定后该日期前的订单不可再继续报销</span
        >
      </span>
    </el-dialog>
    <el-dialog :visible.sync="rejectDialog" title="审核" center width="30%">
      <p>
        <span>审核：</span>
        <el-radio-group>
          <el-radio label="线上品牌商赞助"></el-radio>
          <el-radio label="线下场地免费"></el-radio>
        </el-radio-group>
      </p>
      <el-input
        v-model="rejectReason"
        type="textarea"
        placeholder="请填写原因"
        size="small"
      ></el-input>

      <span slot="footer">
        <el-button
          size="small"
          @click="rejectDialog = false"
          style="margin-top: 10px; margin-left: 10px"
          >取消</el-button
        >
        <el-button
          type="danger"
          size="small"
          @click="directorAudit(rejectId, 1)"
          >确认
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import upload from '@/RayComponents/upload.vue'
import dayjs from 'dayjs'
import axios from 'axios'
import Decimal from 'decimal.js'
import addReimburse from './addReimburse.vue'
import quinn from '../../../utils/quinn'
import store from '../../../store'
import ExcelJS from 'exceljs'
import checkDetail from './checkDetail.vue'

export default {
  name: 'reimbursementPeople',
  components: {
    upload,
    addReimburse,
    checkDetail,
  },
  data() {
    return {
      sateValue: '',
      responsibility: [],
      oneType: [],
      twoType: [],
      baoXiaoType: [
        { value: 1, name: '仓库漏捡、错捡' },
        { value: 2, name: '包装不牢固' },
        { value: 3, name: '安装问题' },
      ],
      baoXiaoStatus: [
        { value: 0, name: '财务待审核' },
        { value: 1, name: '财务待打款' },
        { value: 2, name: '已取消' },
        { value: 3, name: '审核不通过' },
        { value: 4, name: '已打款' },
      ],
      areaData: [],
      apiName: 'newAreaLedgerList',
      params: {
        pageNumber: 1,
        pageSize: 20,
        storeName: '',
        areaId: null,
        systemType: null,
        startTime: '',
        endTime: '',

        // status: null, //报销状态
        // operator: '', //责任主体
      },
      payUrl: '',
      previewPayList: [],
      innerVisible: false,
      buttonShow: false,
      closeDialog: false,
      rejectDialog: false,
      loading: false,
      visible: false,
      innerTitle: '',
      cardNo: '',
      rejectId: {},
      paidUrl: [],
      cardName: '',
      userName: '',
      bankName: '',
      totalCount: 0,
      previewImg: [],
      host: this.$imgHost,
      previewImgList: [],
      systemList: [],
      chooseDateIndex: 1,
      dialogTitle: '',
      rejectReason: '',
      decimalCount: '',
      resFee: '',
      ledgerStatus: false,
      maxHeight: 0,
      typeOptions: [],
      typeList: [],
      createForm: {
        typeId: '',
        provinceId: '',
        voucher: '',
        price: '',
        remark: '',
      },
      orderId: '',
      time: '',
      provinceOptions: [],
      dataList: [],
      authority: [],
      feeData: [],
      arr: [],
      creatorList: [],
    }
  },
  watch: {},
  computed: {
    // processedData() {
    //   return this.dataList.map((row) => {
    //     // 将当前行的list转为 { levelName: money } 的对象，方便快速取值
    //     const listMap = row.list.reduce((map, item) => {
    //       map[item.levelName] = item.money
    //       return map
    //     }, {})

    //     // 返回：保留原始所有字段 + 新增listMap
    //     return { ...row, listMap }
    //   })
    // },
    // dynamicHeaders() {
    //   if (!this.dataList.length) return []

    //   // 1. 收集所有list中的levelName（处理所有行，避免遗漏）
    //   const allLevels = []
    //   this.dataList.forEach((row) => {
    //     row.list.forEach((item) => allLevels.push(item.levelName))
    //   })

    //   // 2. 去重（确保表头不重复）
    //   return [...new Set(allLevels)]
    // },
    preImgs() {
      return this.paidUrl.map((e) => `${this.$imgHost}${e}`)
    },
    headers() {
      const token = this.token || this.$quinn.getStorage('token')
      return {
        token,
      }
    },
  },
  created() {
    this.$api.areaLedgerAreaList().then((res) => {
      this.areaData = res
    })
    this.$api.financeOneType().then((res) => {
      this.oneType = res
    })
    this.$api.financeTwoType().then((res) => {
      this.twoType = res
    })
    this.$api.financeGetOptionerType().then((res) => {
      this.responsibility = res
    })
    this.getSystemType()
    // document.addEventListener('paste', this.handlePaste)
    const { authorityList = [] } = quinn.getStorage('userData')
    const { userName = [] } = quinn.getStorage('userData') || {}
    this.userName = userName
    this.authority = authorityList
  },
  mounted() {
    this.getCostType()
    this.getProvince()
    this.getList()
    this.$nextTick(() => {
      this.maxHeight = window.innerHeight - 340
    })
    window.onresize = () => {
      this.$nextTick(() => {
        this.maxHeight = window.innerHeight - 340
      })
    }
  },
  methods: {
    reset() {
      this.params.pageSize = 20
      this.params.pageNumber = 1
      this.params.storeName = ''
      this.params.areaId = null
      this.params.systemType = null
      this.params.startTime = ''
      this.params.endTime = ''
      this.selectTime = []
      this.getList()
    },
    selectTime(val) {
      if (val) {
        this.params.startTime = dayjs(val[0]).format('YYYY-MM-DD')
        this.params.endTime = dayjs(val[1]).format('YYYY-MM-DD')
      } else {
        this.params.startTime = ''
        this.params.endTime = ''
      }
    },
    transferFunds(row) {
      this.$confirm('确认要打款吗？')
        .then((_) => {
          // this.$api.orderUpdatePayStatus(data).then()
          this.$message.success('操作成功！')
        })
        .catch((_) => {
          return
        })
    },
    review() {
      this.rejectDialog = true
    },
    deteItme() {
      this.$confirm('确认要删除吗？')
        .then((_) => {
          // this.$api.orderUpdatePayStatus(data).then()
          this.$message.success('操作成功！')
        })
        .catch((_) => {
          return
        })
    },
    checkDetail(val) {
      this.$refs.checkDetailRef.handleOpen(val)
    },
    getSystemType() {
      this.$api.orderGetSystemTypeVo().then((res) => {
        this.systemList = res
      })
    },
    reject(row) {
      // this.rejectDialog = true
      // this.rejectReason = ''
      // this.rejectId = row
    },
    editAudit(row) {
      const data = {
        ...row,
        orderName: this.dialogTitle,
        orderId: this.orderId,
      }
      this.$refs.addDialog.handleOpen(data)
    },
    getStatusColor(status) {
      return status === 1
        ? 'orange'
        : status === 2
        ? '#66b1ff'
        : status === 0
        ? 'red'
        : 'transparent'
    },
    getLineColor(status) {
      return status === 1
        ? '1px solid orange'
        : status === 2
        ? '1px solid #66b1ff'
        : status === 0
        ? '1px solid red'
        : 'transparent'
    },
    isRowSelectable(row) {
      return row.status == 4
    },
    wareHousePass(row) {
      this.$api
        .storeLedgerUpdateSupervisorStatus({ storeLedgerId: row.id })
        .then((res) => {
          if (res == 1) {
            this.$message.success('操作成功！')
            this.chooseType(this.chooseDateIndex)
            // this.ledgerStatus=false
            this.getList()
          }
        })
    },
    remoteMethod(val) {
      if (val) {
        const params = {
          accountName: val,
        }
        this.$api.storeLedgerGetAccountName(params).then((res) => {
          this.creatorList = res
        })
      }
    },
    receiveMessage(val) {
      if (val == 1) {
        this.getList()
      }
      if (val == 2) {
        this.$api
          .storeLedgerGetFinanceOneLevelTypeDto({ orderId: this.orderId })
          .then((res) => {
            this.typeList = res
          })
        this.chooseType(this.chooseDateIndex)
        this.getList()
      }
    },
    addReimburse() {
      this.$refs.addDialog.handleOpen()
    },
    closeReimburse() {
      this.closeDialog = true
      this.time = ''
    },
    comfirmClose() {
      this.$api
        .orderCloseOrderReimbursement({ closeTime: this.time })
        .then((res) => {
          if (res == 1) {
            this.closeDialog = false
            this.$message.success('操作成功！')
            this.getList()
          }
        })
    },
    handleSelectionChange(e) {
      if (e.toString()) {
        this.buttonShow = true
      } else {
        this.buttonShow = false
      }
      const _arr = e.map((el) => el.id)
      this.arr = _arr
    },
    handlePaste(event) {
      if (!this.innerVisible) return
      const clipboardData = event.clipboardData || window.clipboardData
      if (clipboardData) {
        for (let i = 0; i < clipboardData.items.length; i++) {
          const item = clipboardData.items[i]
          if (item.kind === 'file' && item.type.startsWith('image/')) {
            const file = item.getAsFile()
            if (file) {
              this.uploadImage(file)
            }
          } else {
            this.$message.error('请拷贝图片!')
            break
          }
        }
      }
    },
    uploadImage(imageFile) {
      const formData = new FormData()
      formData.append('file', imageFile)
      axios
        .post(`${this.$apiHost}/common/fileImgUrl`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            token: store.state.token,
          },
        })
        .then((response) => {
          this.paidUrl.push(response.data.result[0])
          // this.preSalesImgList.push('https://' + response.data.result[0]);
        })
        .catch((error) => {})
    },
    deletePaiedUrl(i) {
      this.paidUrl.splice(i, 1)
    },
    onSuccess(res) {
      console.log(res)
      const { paidUrl = [] } = this
      if (res.code == 200 && res.result) {
        // paidUrl.push(res.result[0]);
        this.paidUrl = res.result
      }
    },
    confirmOrder(val) {
      this.$api.storeLedgerUpdateStoreLedgerStatus({ id: val }).then((res) => {
        this.getList()
      })
    },
    searchList() {
      this.params.pageNumber = 1
      this.getList()
    },
    getList() {
      this.loading = true

      this.$api
        .financeGetFinanceDataReimburseByStoreNameSummaryList(this.params)
        .then(async (res) => {
          console.log('报销明细-店', res)
          // await this.$api.financeTwoType().then((res) => {
          //   console.log('二级结果', res)
          // })
          if (res && res.data.length) {
            this.dataList = res.data
            console.log('----------------', this.dataList)

            this.params.totalCount = res.total
          }
          this.loading = false
        })
    },
    getList2() {
      this.loading = true

      this.$api
        .financeGetFinanceDataReimburseByStoreNameSummaryList(this.params)
        .then(async (res) => {
          console.log('报销明细-店', res)
          // await this.$api.financeTwoType().then((res) => {
          //   console.log('二级结果', res)
          // })
          if (res && res.data.length) {
            const finallyArrayData = [] //最终组合数据
            const linData = res.data //原始数据
            // const zhObj = {} //组合的数据

            const list = []

            const erTypeList = await this.$api.financeTwoType() //二级分类
            // erTypeList.forEach((witem, waiindex) => {
            // const keyValue = `value${witem.id}`
            // const keyName = `name${witem.id}`
            // zhObj[keyValue] = 0
            // zhObj[keyName] = witem.levelName
            // })
            // console.log('组合完的数据', zhObj)
            linData.forEach((item, index) => {
              item.list = []
            })
            if (erTypeList.length) {
              linData.forEach((item, index) => {
                // const earchObj = JSON.parse(JSON.stringify(zhObj))
                erTypeList.forEach((sitem, sindex) => {
                  // 匹配对应
                  // if (item.financeLevelId === sitem.id) {
                  // const keyEarhc = `vlaue${sitem.id}`
                  // earchObj[keyEarhc] = item.money
                  // }

                  item.list.push({
                    levelName: sitem.levelName,
                    money: item.financeLevelId === sitem.id ? item.money : 0,
                  })
                })
              })
              console.log('最终最终最终------', linData)
            }

            this.dataList = linData
            console.log('----------------', this.dataList)

            this.params.totalCount = res.total
            this.loading = false
          }
        })
    },
    getProvince() {
      this.$api.areaLedgerAreaList().then((res) => {
        this.provinceOptions = res
      })
    },
    getCostType() {
      this.$api.areaLedgerFyTypeList().then((res) => {
        this.typeOptions = res
      })
    },
    // submitCreateForm() {
    //   for (let i in this.createForm) {
    //     if (this.createForm[i] == '') {
    //       this.$message.error('请检查信息!');
    //       return;
    //     }
    //   }
    //   this.ledgerStatus = false;
    // },
    handleSizeChange(e) {
      this.params.pageSize = e
      this.getList()
    },
    handleCurrentChange(e) {
      this.params.pageNumber = e
      this.getList()
    },
    async openDialog(row) {
      this.dialogTitle = row.storeName
      this.orderId = row.orderId
      const res = await this.$api
        .storeLedgerGetFinanceOneLevelTypeDto({ orderId: row.orderId })
        .then()
      const resFee = await this.$api
        .orderGetOrderExpressCharge({ orderId: row.orderId })
        .then()
      this.resFee = resFee
      if (resFee) {
        const decimalCount = new Decimal(resFee).div(new Decimal(4))
        this.decimalCount = decimalCount
      }
      this.typeList = res
      this.chooseType(this.chooseDateIndex)
      this.ledgerStatus = true
    },
    handleClose() {},
    chooseType(val) {
      this.chooseDateIndex = val
      this.$api
        .storeLedgerSelectFinanceDetailsByFinanceId({
          financeId: val,
          orderId: this.orderId,
        })
        .then((res) => {
          this.feeData = res
          res.map((a) => {
            a.proof.forEach((el) => {
              this.previewImgList.push(this.host + el)
            })
          })
        })
    },
    comfirmAudit(val, type) {
      const data = {
        status: 1,
        id: val.id,
        rejectReason: this.rejectReason,
      }
      if (type == 3) {
        data.status = 0
        delete data.rejectReason
      }
      this.$api.storeLedgerUpdateStoreLedgerFinanceStatus(data).then((res) => {
        if (res == 1) {
          this.$message({ message: '操作成功!', type: 'success' })
          this.$api
            .storeLedgerGetFinanceOneLevelTypeDto({ orderId: this.orderId })
            .then((res) => {
              this.typeList = res
            })
          this.chooseType(this.chooseDateIndex)
          this.rejectDialog = false
          this.getList()
        }
      })
    },
    directorAudit(val, type) {
      const data = {
        status: type,
        rejectReason: this.rejectReason,
        storeLedgerId: val.id,
      }
      this.$api.storeLedgerUpdateSupervisorStatus(data).then((res) => {
        if (res == 1) {
          this.$message({ message: '操作成功!', type: 'success' })
          this.$api
            .storeLedgerGetFinanceOneLevelTypeDto({ orderId: this.orderId })
            .then((res) => {
              this.typeList = res
            })
          this.chooseType(this.chooseDateIndex)
          this.rejectDialog = false
          this.getList()
        }
      })
    },
    checkPayType(val) {
      this.payId = val.id
      this.innerVisible = true
      this.paidUrl = []
    },
    async comfirmPay() {
      if (!this.paidUrl) {
        return this.$message.warning('请财务上传已付款凭证！')
      }
      const result = this.arr.map((value) => ({
        id: value,
        status: 3,
        paidUrl: this.paidUrl.toString(),
      }))
      const res = await this.$api
        .storeLedgerUpdateStoreLedgerFinanceStatus2(result)
        .then()
      if (res == 1) {
        this.innerVisible = false
        this.getList()
        this.$api
          .storeLedgerGetFinanceOneLevelTypeDto({ orderId: this.orderId })
          .then((res) => {
            this.typeList = res
          })
        this.chooseType(this.chooseDateIndex)
      }
      // const promises = this.arr.map(el => {
      //   const data = {
      //     id: el,
      //     status: 3,
      //     paidUrl: this.paidUrl.toString()
      //   };
      //   return this.$api.storeLedgerUpdateStoreLedgerFinanceStatus2(data).then(res => {
      //     if (res === 1) {
      //       return Promise.resolve();
      //     } else {
      //       return Promise.reject("操作失败");
      //     }
      //   });
      // });

      // Promise.all(promises)
      //     .then(() => {
      //       this.$message({message: "操作成功!", type: "success"});
      //       this.innerVisible = false;
      //       this.getList()
      //       this.$api.storeLedgerGetFinanceOneLevelTypeDto({orderId: this.orderId}).then(res => {
      //         this.typeList = res
      //       })
      //       this.chooseType(this.chooseDateIndex)
      //     })
      //     .catch(error => {
      //       this.$message.error(error || "部分操作失败");
      //     });
    },
    //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线 //分割线
    async deleteAudit(row) {
      const r = await this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch(() => null)
      if (r) {
        const res = await this.$api
          .storeLedgerDeleteOrUpdateStoreLedger({ id: row.id })
          .catch(() => null)
        if (res == 1) {
          this.$message.success('操作成功!')
          this.chooseType(this.chooseDateIndex)
        }
      }
    },
    getImageBase64(url) {
      return new Promise((resolve, reject) => {
        const img = new Image()
        img.crossOrigin = 'anonymous'
        img.onload = function () {
          try {
            const canvas = document.createElement('canvas')
            canvas.width = img.width
            canvas.height = img.height
            const ctx = canvas.getContext('2d')
            ctx.drawImage(img, 0, 0)
            console.log(ctx, 'ctx')
            resolve(canvas.toDataURL('image/jpeg')) // ✅ 修正为标准 MIME
          } catch (e) {
            reject(e)
          }
        }
        img.onerror = reject
        img.src = url + (url.includes('?') ? '&' : '?') + 'v=' + Date.now() // 防缓存
      })
    },

    async downDetail(row) {
      this.downIsLoad = true
      const res = await this.$api.storeLedgerGetStoreReimburseDetail({
        orderId: row.orderId,
      })
      this.$message('正在导出，请稍等~')
      const workbook = new ExcelJS.Workbook()
      const worksheet = workbook.addWorksheet('Sheet1')
      const headers = [
        '申请人',
        '申请日期',
        '费用类型',
        '承担主体',
        '费用说明',
        '金额/花费',
        '备注',
        '凭证',
        '付款方式',
        '财务付款凭证',
        '状态',
      ]
      const titleRow = worksheet.addRow(headers)
      worksheet.columns = headers.map((item, index) => {
        if (index == 4) {
          // 交易截图
          return {
            width: 80,
            alignment: { vertical: 'middle', horizontal: 'center' }, // 所有列居中
          }
        } else {
          return {
            width: 20,
            alignment: { vertical: 'middle', horizontal: 'center' }, // 所有列居中
          }
        }
      })
      // 标题样式
      titleRow.eachCell((cell) => {
        cell.fill = {
          type: 'pattern',
          pattern: 'solid',
          fgColor: { argb: '800080' },
        }
        cell.font = { bold: true, color: { argb: 'FFFFFF' } }
        cell.alignment = {
          wrapText: true, // 自动换行
          vertical: 'middle', // 垂直居中
          horizontal: 'center', // 水平居中（可按需）
        }
      })
      for (const el of res) {
        const statusMap = [
          '待主管审核',
          '已驳回',
          '待付款',
          '已付款',
          '待财务审核',
        ]
        el.storeTypeName = statusMap[el.status] || ''
        const rowItem = worksheet.addRow([
          el.userName,
          el.createTime,
          el.levelName,
          el.optioner,
          el.matter,
          el.money,
          el.remark,
          // el.rejectReason,
          '',
          '',
          '',
          el.storeTypeName,
        ])
        const images = Array.isArray(el.proof)
          ? el.proof
          : el.proof
          ? [el.proof]
          : []
        const images1 = Array.isArray(el.payUrl)
          ? el.payUrl
          : el.payUrl
          ? [el.payUrl]
          : []
        const images2 = Array.isArray(el.paidUrl)
          ? el.paidUrl
          : el.paidUrl
          ? [el.paidUrl]
          : []
        const imageHeight = 80
        const imageWidth = 100
        const gap = 10
        if (images.length > 0) {
          worksheet.getRow(rowItem.number).height = imageHeight + 10
          const imageGroups = [
            { list: images, col: 7 },
            { list: images1, col: 8 },
            { list: images2, col: 9 },
          ]
          for (const group of imageGroups) {
            const list = group.list || []
            const baseCol = group.col

            for (let i = 0; i < list.length; i++) {
              try {
                const base64 = await this.getImageBase64('https://' + list[i])
                const imageId = workbook.addImage({ base64, extension: 'jpeg' })
                worksheet.addImage(imageId, {
                  tl: {
                    col: baseCol,
                    row: rowItem.number - 1,
                    colOff: i * (imageWidth + gap),
                  },
                  ext: { width: imageWidth, height: imageHeight },
                })
              } catch (err) {
                console.warn(`图片插入失败 (第${baseCol}列):`, list[i], err)
              }
            }
          }
        }
      }

      const buffer = await workbook.xlsx.writeBuffer()
      saveAs(new Blob([buffer]), `${row.storeName}.xlsx`)
    },
  },
}
</script>

<style lang="less" scoped>
.topSearch {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  span {
    display: inline-block;
    margin-right: 15px;
    margin-bottom: 10px;
  }
}

.amountContainer {
  width: 100%;
  text-align: center;
}

.amountContainer > div:nth-child(1) {
  margin-bottom: 10px;
}

/deep/ .el-dialog__header {
  background-color: #0f79e2;
  //border-top-left-radius: 20px;
  //border-top-right-radius: 20px;
}

/deep/ .el-dialog__title {
  color: #fff;
}

/deep/ .center {
  border-radius: 20px;
}

/deep/ .el-dialog__headerbtn .el-dialog__close {
  color: #fff;
}

.feeType {
  display: flex;
  justify-content: center;
}

.typeList {
  width: 150px;
  height: 60px;
  color: #000000;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
  background: linear-gradient(to left, #b3d8ff, #b3d8ff) left top no-repeat,
    linear-gradient(to bottom, #b3d8ff, #b3d8ff) left top no-repeat,
    linear-gradient(to left, #b3d8ff, #b3d8ff) right top no-repeat,
    linear-gradient(to bottom, #b3d8ff, #b3d8ff) right top no-repeat,
    linear-gradient(to left, #b3d8ff, #b3d8ff) left bottom no-repeat,
    linear-gradient(to bottom, #b3d8ff, #b3d8ff) left bottom no-repeat,
    linear-gradient(to left, #b3d8ff, #b3d8ff) right bottom no-repeat,
    linear-gradient(to left, #b3d8ff, #b3d8ff) right bottom no-repeat;
  background-size: 1px 20px, 20px 1px, 1px 20px, 20px 1px;

  span {
    cursor: default;
  }
}

.active {
  box-shadow: inset 0 0 16px 0 #66b1ff;
  font-size: 16px;
  font-weight: bolder;
}
</style>
